package com.ruitu.mall_98_1.product.activity;

import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.beanu.arad.Arad;
import com.beanu.arad.base.my_base.Config;
import com.beanu.arad.base.my_base.MyBaseActivity;
import com.beanu.arad.utils.AppUtils;
import com.beanu.arad.utils.ToastUtils;
import com.beanu.arad.utils.UIUtils;
import com.beanu.arad.widget.progressactivity.ProgressLayout;
import com.ruitu.mall_98_1.R;
import com.ruitu.mall_98_1.dao.P_Global;
import com.ruitu.mall_98_1.dao.api.APIRetrofit;
import com.ruitu.mall_98_1.product.fragment.ShopDetail1Fragment;
import com.ruitu.mall_98_1.product.fragment.ShopDetail2Fragment;
import com.ruitu.mall_98_1.product.fragment.ShopDetail3_new_Fragment;
import com.ruitu.mall_98_1.product.fragment.ShopDetail4Fragment;
import com.ruitu.router_module.AppHolder;
import com.ruitu.router_module.CommonUtils;
import com.ruitu.router_module.bean.EventModel;
import com.ruitu.router_module.bean.api.BaseResult;
import com.ruitu.router_module.bean.api.SubscriberImpl;
import com.ruitu.router_module.bean.product.Company;
import com.ruitu.router_module.bean.product.ShopDetail;
import com.ruitu.router_module.utils.GlideUtil;
import com.ruitu.router_module.utils.MapNavUtil;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;
import java.util.Map;

import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

//企业
public class ShopDetailActivity extends MyBaseActivity {
    private ViewPager viewpager;//
    private TabLayout tab;
    private TextView tv_follow, tv_nav, tv_name, tv_close;//关注企业,导航,名称,关闭
    private ImageView icon;//企业头像
    private LinearLayout ll_divider;//tab的分割线

    private VpAdapter adapter;

    private String companyId;//传过来的企业id
    private ShopDetail shopDetail;//请求得到的企业详情
    public Company company;//请求得到的企业对象

    @Override
    protected int getLayoutRes() {
        return R.layout.activity_shop_detail;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (Arad.bus.isRegistered(this)) {
            Arad.bus.unregister(this);
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle instanceState) {
        super.onSaveInstanceState(instanceState);
        instanceState.clear();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGetEvent(EventModel e) {
        if (e.getEventCode() == 18113051) {//首页点击更多商品
//            viewpager.setCurrentItem(2, true);
//            Bundle bundle = new Bundle();
//            bundle.putSerializable("product_list", (Serializable) shopDetail.getGoodsList());
//            startActivity(ProductListActivity.class, bundle);

            // 折中方案 并不可取
            P_Global.productList = shopDetail.getGoodsList();
            startActivity(ProductListActivity.class);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        viewpager = findViewById(R.id.viewpager);
        tv_follow = findViewById(R.id.tv_follow);
        tv_nav = findViewById(R.id.tv_nav);
        tv_name = findViewById(R.id.tv_name);
        tv_close = findViewById(R.id.tv_close);
        icon = findViewById(R.id.icon);
        tab = findViewById(R.id.tab);
        ll_divider = findViewById(R.id.ll_divider);

        companyId = getIntent().getExtras().getString("companyId");//传过来的企业id
        tab.setTabMode(TabLayout.MODE_FIXED);
        viewpager.setOffscreenPageLimit(9);

        tv_follow.setOnClickListener(this);
        tv_nav.setOnClickListener(this);
        tv_close.setOnClickListener(this);

        disableSlideBack();
        Arad.bus.register(this);
        showProgress();
        reqShopDetail();
    }

    private void reqCollectShop() {//关注企业
        hideProgress();
        if (CommonUtils.isLoginToActivity(this)) {
            showProgressWithText(true, "正在关注...");
            APIRetrofit.getDefault().reqCollect(AppHolder.instance().getUser().getAccountId(), "2", company.getId())
                    .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new SubscriberImpl<BaseResult>() {
                        @Override
                        public void onError(Throwable e) {
                            hideProgress();
                            e.printStackTrace();
                            ToastUtils.showShort("操作失败");
                        }

                        @Override
                        public void onNext(BaseResult baseResult) {
                            hideProgress();
                            if (baseResult.isSuccess()) {
                                ToastUtils.showShort("关注成功!");
                                reqShopDetail();
                            } else {
                                ToastUtils.showShort(baseResult.getMsg());
                            }
                        }
                    });
        } else {
            ToastUtils.showShort("请先登录");
        }
    }

    private void reqCollectCancel() {//取消关注企业
        if (null != shopDetail && null != shopDetail.getCollection()) {
            hideProgress();
            showProgressWithText(true, "正在取消关注...");
            APIRetrofit.getDefault().reqCollectCancel(AppHolder.instance().getUser().getAccountId(), "2"
                    , shopDetail.getCollection().getId())
                    .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new SubscriberImpl<BaseResult>() {
                        @Override
                        public void onError(Throwable e) {
                            hideProgress();
                            e.printStackTrace();
                            ToastUtils.showShort("操作失败");
                        }

                        @Override
                        public void onNext(BaseResult baseResult) {
                            hideProgress();
                            if (baseResult.isSuccess()) {
                                ToastUtils.showShort("已取消关注");
                                reqShopDetail();
                            } else {
                                ToastUtils.showShort(baseResult.getMsg());
                            }
                        }
                    });
        }
    }

    private void reqShopDetail() {
        String accountId = CommonUtils.isLogin() ? AppHolder.instance().getUser().getAccountId() : "";
        APIRetrofit.getDefault().reqShopDetail(companyId, accountId)
                .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SubscriberImpl<BaseResult<ShopDetail>>() {
                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                        hideProgress();
                    }

                    @Override
                    public void onNext(BaseResult<ShopDetail> detailResult) {
                        if (detailResult.isSuccess()) {
                            shopDetail = detailResult.getData();
                            if (null != shopDetail) {
                                company = shopDetail.getCompany();
                            }
                            setCompanyInfo();
                            ll_divider.setVisibility(View.VISIBLE);//显示分割线
                            adapter = new VpAdapter(getSupportFragmentManager());
                            viewpager.setAdapter(adapter);
                            tab.setupWithViewPager(viewpager);
                        } else {
                            ToastUtils.showShort(detailResult.getMsg());
                        }
                        hideProgress();
                    }
                });
    }

    //设置企业信息
    private void setCompanyInfo() {
        if (null != shopDetail && null != company) {
            tv_name.setText(company.getName());
            GlideUtil.loadImg(Config.BASE_URL + company.getImageUrl(), icon);
            if (null != shopDetail.getCollection() && !TextUtils.isEmpty(shopDetail.getCollection().getId())) {//说明是已经关注的企业
                tv_follow.setText("取消关注");
            } else {
                tv_follow.setText("关注企业");
            }
        }
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        if (v == tv_follow) {
            if (null != shopDetail) {
                if (null != shopDetail.getCollection() &&
                        !TextUtils.isEmpty(shopDetail.getCollection().getId())) {
                    reqCollectCancel();//说明已经关注,点击取消关注
                } else {//说明还没关注企业
                    reqCollectShop();
                }
            } else {
                ToastUtils.showShort("企业信息加载中,请稍后再试");
            }
        }
        if (v == tv_close) {//关闭
            finish();
        }
        if (v == tv_nav) {//导航 (需要定位当前位置)
            startaNav();
        }
    }


    //开始导航
    private void startaNav() {
        if (AppUtils.isInstallApp(MapNavUtil.BAIDUMAP_PACKAGENAME)) {//已安装百度地图
            if (null == company) {
                ToastUtils.showShort("企业信息加载中,请稍候重试");
                return;
            }

            Company.CompanyInfo comInfo = company.getCompanyInfo();
            if (null == comInfo) {
                ToastUtils.showShort("企业信息有误,请联系客服");
                return;
            }
            if (TextUtils.isEmpty(comInfo.getLng()) || TextUtils.isEmpty(comInfo.getLat())) {
                ToastUtils.showShort("企业位置有误,请联系客服");
                return;
            }

            Map map = new HashMap();
//                map.put(MapNavUtil.BD_LNG, P_Global.CURR_LNG);//118.309952,35.073284
//                map.put(MapNavUtil.BD_LAT, P_Global.CURR_LAT);
            map.put(MapNavUtil.BD_LNG, comInfo.getLng());//118.309341,35.073686
            map.put(MapNavUtil.BD_LAT, comInfo.getLat());
            map.put(MapNavUtil.DESTINATION, company.getName());
            MapNavUtil.invokeBaiDuMap(this, map);
        } else {
            UIUtils.showAlertDialog(getSupportFragmentManager(), "温馨提示", "该功能需要安装百度地图，是否前往应用市场下载？",
                    "去下载", "取消"
                    , new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Uri uri = Uri.parse("market://details?id=" + MapNavUtil.BAIDUMAP_PACKAGENAME);
                            Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
                            try {
                                startActivity(goToMarket);
                            } catch (ActivityNotFoundException e) {
                                e.printStackTrace();
                            }
                        }
                    }, null);
        }

//        if (PermissionUtil.isHasPer(this, Permission.ACCESS_COARSE_LOCATION, Permission.ACCESS_FINE_LOCATION)) {
//            if (P_Global.CURR_LNG == 0 || P_Global.CURR_LNG == P_Global.BAIDU_LOC_ERROR) {
//                ToastUtils.showShort("正在定位,请稍后再试");
//                return;
//            }
//        } else {
//            ToastUtils.showShort("该功能需要定位您当前的位置");
//            PermissionUtil.handleMultiPermission(this, "定位", new PermissionUtil.PermissionListener() {
//                @Override
//                public void onPermissionOk(boolean isOk) {
//                }
//
//                @Override
//                public void onOpenPermissionPage(boolean isOpen) {
//                }
//            }, Permission.ACCESS_COARSE_LOCATION, Permission.ACCESS_FINE_LOCATION);
//        }
    }

    //设置店铺底部的数据
    public void setShopBottom(TextView tv1, TextView tv2, TextView tv3, TextView tv4) {
        try {
            tv1.setText(company.getName() + " 版权所有");
            tv2.setText("联系电话:" + company.getCompanyInfo().getCompanyPhone());
            tv3.setText("地址:" + company.getCompanyInfo().getCompanyAddress());
            tv4.setText("技术支持:" + "济南锐途信息技术有限公司");
        } catch (Exception e) {
        }
    }

    private class VpAdapter extends FragmentPagerAdapter {
        private String[] titles = {"企业商城", "关于我们", "生产中心", "联系我们"};

        public VpAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            if (position == 0) {
                return ShopDetail1Fragment.newInstance(shopDetail);
            } else if (position == 1) {
                return ShopDetail2Fragment.newInstance();
            } else if (position == 2) {
                return ShopDetail3_new_Fragment.newInstance(shopDetail);
            } else if (position == 3) {
                return ShopDetail4Fragment.newInstance();
            }
            return ShopDetail1Fragment.newInstance(shopDetail);
        }

        @Override
        public int getCount() {
            return 4;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return titles[position];
        }

        @Override
        public Parcelable saveState() {
            return super.saveState();
        }
    }

    protected ProgressLayout findProgressLayout() {
        return null;
    }
}
